package com.zlm.mall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zlm.common.utils.PageUtils;
import com.zlm.common.utils.Query;
import com.zlm.mall.product.dao.CategoryDao;
import com.zlm.mall.product.entity.CategoryEntity;
import com.zlm.mall.product.service.CategoryBrandRelationService;
import com.zlm.mall.product.service.CategoryService;
import com.zlm.mall.product.vo.Catelog2Vo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Resource
    private CategoryBrandRelationService categoryBrandRelationService;

    @Resource
    RedisTemplate<String, String> redisTemplate;

    @Resource
    RedissonClient redissonClient;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {

        //1查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //组装父子的树形结构
        //找到所有的一级分类
        List<CategoryEntity> menus = entities.stream().filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .map(menu -> {
                    menu.setChildren(getChildren(menu, entities));
                    return menu;
                }).sorted((menu1, menu2) -> (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort()))
                .collect(Collectors.toList());
        return menus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 检查当前删除的菜单是否被别的地方引用

        //逻辑删除
        baseMapper.deleteBatchIds(asList);

    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> list = new ArrayList<>();
        list.add(catelogId);
        list = findParentPath(catelogId, list);
        //倒序
        Collections.reverse(list);
        return list.toArray(new Long[list.size()]);
    }

    /**
     * 级联更新所有关联数据
     * @CacheEvict 删除缓存
     *
     * 同时删除多个缓存
     * 1)  @Caching(evict = {
     * //            @CacheEvict(value="categorys",key = "'getLevel1Categorys'"),
     * //            @CacheEvict(value="categorys",key = "'getCategoryJson'")
     * //
     * //    })
     * 2)  @CacheEvict(value = "categorys",allEntries = true)
     *
     * @param category
     */
    //@CacheEvict(value = {"categorys"},key="'getLevel1Categorys'")
//    @Caching(evict = {
//            @CacheEvict(value="categorys",key = "'getLevel1Categorys'"),
//            @CacheEvict(value="categorys",key = "'getCategoryJson'")
//
//    })
    @CacheEvict(value = "categorys",allEntries = true)
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        if (StringUtils.isNotBlank(category.getName())) {
            categoryBrandRelationService.updateCategoryName(category.getCatId(), category.getName());
        }

    }

    private List<Long> findParentPath(Long catelogId, List<Long> list) {
        CategoryEntity categoryEntity = this.getById(catelogId);
        while (categoryEntity.getParentCid() != 0) {
            CategoryEntity entity = this.getById(categoryEntity.getParentCid());
            list.add(entity.getCatId());
            categoryEntity = entity;
        }
        return list;
    }


    private List<CategoryEntity> getChildren(CategoryEntity entity, List<CategoryEntity> entities) {

        List<CategoryEntity> list = entities.stream().filter(category -> category.getParentCid() == entity.getCatId())
                .map(category -> {
                    category.setChildren(getChildren(category, entities));
                    return category;
                }).sorted((menu1, menu2) -> (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort()))
                .collect(Collectors.toList());

        return list;
    }

    /**
     * 设置缓存 key   key=""
     * 设置缓存ttl   yml里配置 spring.redis.time-to-live   毫秒
     * 保存为json
     * @return
     */
    @Cacheable(value={"categorys"},key = "#root.methodName")
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        System.out.println("getLevel1Categorys()......");
        List<CategoryEntity> list = this.list(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return list;
    }

    @Cacheable(value="categorys",key="#root.methodName")
    @Override
    public Map<String, List<Catelog2Vo>> getCategoryJson() {
        Map<String, List<Catelog2Vo>> categoryJsonFromOb = getCategoryJsonFromObWithRedissonLock();
        return categoryJsonFromOb;
    }

    public Map<String, List<Catelog2Vo>> getCategoryJson2() {
        /**
         * 缓存null值 解决缓存穿透
         * 设置随机过期时间  解决缓存雪崩
         * 加锁 解决缓存击穿
         */
        //加入缓存
        String catalogJson = redisTemplate.opsForValue().get("catalogJson");
        if (StringUtils.isBlank(catalogJson)) {
            log.info("缓存不命中...查询数据库...");
            Map<String, List<Catelog2Vo>> categoryJsonFromOb = getCategoryJsonFromObWithRedissonLock();
            return categoryJsonFromOb;
        }
        log.info("缓存命中....");
        //string转为对象
        Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {
        });
        return result;

    }

    //从数据库查询数据 使用redisson分布式锁
    public Map<String, List<Catelog2Vo>> getCategoryJsonFromObWithRedissonLock() {

        //使用redisson分布式锁
        RLock lock = redissonClient.getLock("catelogJson");
        //加锁
        lock.lock();
        Map<String, List<Catelog2Vo>> dataFromDb;
        try {
            //获取分布式锁成功.. 执行业务
            log.info("获取分布式锁成功.. 执行业务");
            dataFromDb = getDataFromDb();
        } finally {
            lock.unlock();
        }
        return dataFromDb;

    }


    //从数据库查询数据 使用redis分布式锁 +lua脚本原子删锁
    public Map<String, List<Catelog2Vo>> getCategoryJsonFromObWithRedisLuaLock() {

        //使用分布式锁 使用随机值,防止被别的线程删除非自己的锁
        String uuid = UUID.randomUUID().toString();
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 5, TimeUnit.SECONDS);
        if (aBoolean) {
            Map<String, List<Catelog2Vo>> dataFromDb;
            try {
                //获取分布式锁成功.. 执行业务
                log.info("获取分布式锁成功.. 执行业务");
                dataFromDb = getDataFromDb();
            } finally {
                //删除锁
                //使用lua删除锁
                String script = " if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
                redisTemplate.execute(new DefaultRedisScript<Long>(script,Long.class),Arrays.asList("lock"),uuid);
            }

            return dataFromDb;
        }else{
            //加锁失败重试
            log.info("分布式锁获取失败重试");
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return getCategoryJsonFromObWithRedisLuaLock();

        }
    }

    //从数据库查询数据 使用redis分布式锁
    public Map<String, List<Catelog2Vo>> getCategoryJsonFromObWithRedisLock() {

        //使用分布式锁
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent("lock", "lock", 5, TimeUnit.SECONDS);
        if (aBoolean) {
            //加锁成功.. 执行业务
            Map<String, List<Catelog2Vo>> dataFromDb = getDataFromDb();
            //删除锁
            redisTemplate.delete("lock");
            return dataFromDb;
        }else{
            //加锁失败重试
            return getCategoryJsonFromObWithRedisLock();
        }
    }

    private Map<String, List<Catelog2Vo>> getDataFromDb() {
        //再次查询缓存
        String catalogJson = redisTemplate.opsForValue().get("catalogJson");
        if (StringUtils.isNotBlank(catalogJson)) {
            //string转为对象
            log.info("查询了数据库...");
            Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });
            return result;
        }
        /**
         * 优化
         * 1)查出所有
         */
        List<CategoryEntity> categoryEntities = this.list();

        //查询所有一级分类
        List<CategoryEntity> level1Categorys = getParent_cid(categoryEntities, 0L);
        Map<String, List<Catelog2Vo>> collect = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //查询每个分类的二级分类
            List<CategoryEntity> list = getParent_cid(categoryEntities, v.getCatId());
            List<Catelog2Vo> catelog2Vos = null;
            if (list != null && list.size() > 0) {
                catelog2Vos = list.stream().map(leve2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, leve2.getCatId().toString(), leve2.getName());
                    //查询三级分类
                    List<CategoryEntity> entities = getParent_cid(categoryEntities, leve2.getCatId());
                    List<Catelog2Vo.Catalog3Vo> catalog3Vos = null;
                    if (entities != null && entities.size() > 0) {
                        //封装三级分类
                        catalog3Vos = entities.stream().map(leve3 -> {
                            Catelog2Vo.Catalog3Vo catalog3Vo = new Catelog2Vo.Catalog3Vo(leve2.getCatId().toString(), leve3.getCatId().toString(), leve3.getName());
                            return catalog3Vo;
                        }).collect(Collectors.toList());

                    }
                    catelog2Vo.setCatalog3List(catalog3Vos);
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }

            return catelog2Vos;
        }));
        //放入缓存
        redisTemplate.opsForValue().set("catalogJson", JSON.toJSONString(collect));
        return collect;
    }


    //从数据库查询数据 使用synchronized加锁
    public Map<String, List<Catelog2Vo>> getCategoryJsonFromOb() {

        synchronized (this) {

            return getDataFromDb();
        }


    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> categoryEntities, Long parent_cit) {
        //return this.baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
        //从所有分类里查parent_id的分类
        List<CategoryEntity> collect = categoryEntities.stream().filter(item -> item.getParentCid() == parent_cit)
                .collect(Collectors.toList());
        return collect;

    }
}
